package com.feng.seata.utils;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.yaml.snakeyaml.Yaml;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * @author yinglong.zhang
 * @description
 * @date 2024-1-24 17:19
 */
public class YmlUtils {

    private YmlUtils(){
    }

    public static final String ACTIVE_YML_FILE = "application.yml";
    private static String active;

    static {
        active = getYmlConfig(ACTIVE_YML_FILE, "spring.profiles.active");
    }
    /**
     * @param ymlName 配置文件路径
     * @param key     查找的配置键
     * @return
     */
    public static String getYmlConfig(String ymlName, String key) {
        String[] split = key.split("\\.");
        Yaml yaml = new Yaml();
        InputStream inputStream;
        Resource resource;
        try {
            resource = new ClassPathResource(ymlName);
            inputStream = resource.getInputStream();
            Map<String, Object> load = yaml.loadAs(inputStream, Map.class);
            for (int i = 0; i < split.length; i++) {
                if (i == split.length - 1) {
                    return (String) load.get(split[i]);
                } else {
                    load = (Map<String, Object>) load.get(split[i]);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 配置键查找profile内的配置值
     *
     * @param key
     * @return
     */
    public static String getYmlConfig(String key) {
        String[] split = key.split("\\.");
        Yaml yaml = new Yaml();
        InputStream inputStream;
        Resource resource;
        try {
            resource = new ClassPathResource("application-" + active + ".yml");
            inputStream = resource.getInputStream();
            Map<String, Object> load = yaml.loadAs(inputStream, Map.class);
            for (int i = 0; i < split.length; i++) {
                if (i == split.length - 1) {
                    return (String) load.get(split[i]);
                } else {
                    load = (Map<String, Object>) load.get(split[i]);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
